package com.sim.simserial.ui

import android.annotation.SuppressLint
import android.util.Log
import android.widget.ImageView
import androidx.core.os.bundleOf
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import com.drake.brv.utils.addModels
import com.drake.brv.utils.grid
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.drake.channel.receiveEvent
import com.drake.tooltip.toast
import com.infinit.selfhelp.common.base.ViewBindingFragment
import com.sim.simserial.R
import com.sim.simserial.databinding.FragmentGoodsBinding
import com.sim.simserial.databinding.ItemGoodsBinding
import com.sim.simserial.databinding.ItemGoodsCategoryBinding
import com.sim.simserial.dialog.ShoppingCartDialogFragment
import com.sim.simserial.dialog.ShoppingCartDialogFragment.Companion.GOODS
import com.sim.simserial.navigation.MainNavigator
import com.sim.simserial.viewmodel.SimViewModel
import com.sim.storage.GoodsBean
import com.sim.storage.GoodsBeanParent
import com.sim.storage.GoodsCategoryData
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class GoodsHomeFragment : ViewBindingFragment<FragmentGoodsBinding>(R.layout.fragment_goods) {

    private var beanList: List<GoodsBean>? = null
    private var goodsCategoryData: List<GoodsCategoryData>? = null

    @Inject
    lateinit var homeNavigator: MainNavigator
    private var goods: GoodsBeanParent? = null
    private val simViewModel by viewModels<SimViewModel>()

    var orderGoodsBean = mutableListOf<GoodsBean>()

    override fun initData() {
        super.initData()
        simViewModel.getGoodsCategory()
        simViewModel.getGoodsList()
    }

    override fun initView() {
        super.initView()
        mBinding.rvTitles.linear().setup {
            addType<GoodsCategoryData>(R.layout.item_goods_category)
            onBind {
                val content = getModel<GoodsCategoryData>()
                getBinding<ItemGoodsCategoryBinding>().root.setOnClickListener {
                    (models?.find { (it as? GoodsCategoryData)?.isSelect == true } as? GoodsCategoryData)?.isSelect = false
                    content.isSelect = !content.isSelect
                    (this.adapter).notifyDataSetChanged()

                    beanList = goods?.goods?.find { it.category == content.name }?.list
                    mBinding.rv.models = beanList
                }
            }
        }.models = goodsCategoryData ?: emptyList()


        mBinding.rv.grid(2).setup { adapter ->
            addType<GoodsBean>(R.layout.item_goods)
            onBind {
                val model = getModel() as? GoodsBean
                model?.urlId?.let { findView<ImageView>(R.id.img).setImageResource(it) }
                val binding = getBinding<ItemGoodsBinding>()
                binding.imgAdd.setOnClickListener {
                    if (model != null) {
                        homeNavigator.toCoffeeDetail(model.copy())
                    }
                }
                binding.tvPrice.text = model?.getPrice()
            }
        }.models = beanList ?: emptyList()
        updateView()
    }

    override fun onEvent() {
        mBinding.clPrice.setOnClickListener {
            if (orderGoodsBean.isNotEmpty()) {
                val shoppingCartDialogFragment = ShoppingCartDialogFragment()
                shoppingCartDialogFragment.arguments = bundleOf().apply {
                    putParcelableArrayList(GOODS, ArrayList(orderGoodsBean))
                }
                shoppingCartDialogFragment.show(childFragmentManager, "ShoppingCartDialogFragment")
            }
        }
        mBinding.tvOrder.setOnClickListener {
            if (orderGoodsBean.isNotEmpty()) {
                homeNavigator.toOrderDetail(orderGoodsBean)
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun observe() {
        super.observe()
        setFragmentResultListener("CoffeeDetailFragment") { _, bundle ->
            bundle.getParcelable<GoodsBean>("goods")?.let { goodsBean ->
                orderGoodsBean.add(goodsBean)

                mBinding.rv.models?.map { itemGoodsBean ->
                    if ((itemGoodsBean as GoodsBean).name == goodsBean.name) {
                        itemGoodsBean.count += 1
                    }
                }
                (mBinding.rv.adapter)?.notifyDataSetChanged()
            }
            Log.d("CoffeeDetailFragment---", "${bundle.getParcelable<GoodsBean>("goods")?.toString()}")
            mBinding.tvPriceValue.text = orderGoodsBean.map { it.getPriceFloat() }.sum().toString()
        }

        receiveEvent<SimViewModel.GoodsCategoryEvent> {
            goodsCategoryData = it.list
            mBinding.rvTitles.models = it.list
        }
        receiveEvent<SimViewModel.GoodsListEvent> {
            goods = it.goods
            beanList = it.goods.goods.first().list
            mBinding.rv.addModels(beanList)
        }
        receiveEvent<OrderDetailFragment.SaleSuccess> {
            orderGoodsBean.clear()
        }
    }

    private fun updateView() {
        mBinding.tvPriceValue.text = orderGoodsBean.map { it.getPriceFloat() }.sum().toString()
        mBinding.rv.models?.map { itemGoodsBean ->
            itemGoodsBean as GoodsBean
            itemGoodsBean.count = orderGoodsBean.filter { it.name == itemGoodsBean.name }.size
        }
        (mBinding.rv.adapter)?.notifyDataSetChanged()
    }
}